import java.util.PriorityQueue;

//定时器的任务
class MyTimerTask implements Comparable<MyTimerTask> {
    //描述任务是什么
    private Runnable runnable;
    //通过毫秒时间戳，表示这个任务具体啥时候执行
    private long time;

    public MyTimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        //获取当前时间戳 + delay，得到一个绝对的时间戳
        this.time = System.currentTimeMillis() + delay;
    }

    public void run() {
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        //此处 - 的顺序就决定了这里是大堆还是小堆
        return (int) (this.time - o.time);
    }
}

class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private static Object locker = new Object();

    public MyTimer() {
        //创建线程，负责执行上述队列中的内容
        Thread t = new Thread(() -> {
            try {
                //我们也不知里面有多少个元素，就需要不停地循环去取
                while (true) {
                    synchronized (locker) {
                        //在队列不为空的情况下，取出对首元素
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask current = queue.peek();
                        if (System.currentTimeMillis() >= current.getTime()) {
                            //执行任务,调用 runnable 里面的 run，真正的开始执行任务无逻辑
                            current.run();
                            //把执行过的任务，从队列中删除
                            queue.poll();
                        } else {
                            //不执行任务
                            locker.wait(current.getTime() - System.currentTimeMillis());
                        }
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t.start();
    }

    public void schedule(Runnable runnable, long delay) {
        MyTimerTask myTimerTask = new MyTimerTask(runnable, delay);
        synchronized (locker) {
            queue.offer(myTimerTask);
            locker.notify();
        }
    }
}

public class Demo6 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(() -> {
            System.out.println("hello 3000");
        }, 3000);
        myTimer.schedule(() -> {
            System.out.println("hello 2000");
        }, 2000);
        myTimer.schedule(() -> {
            System.out.println("hello 1000");
        }, 1000);
        System.out.println("程序开始执行");
    }
}
